package com.ben.multiple.elasticsearch;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.json.PackageVersion;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.MonthDayDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.YearDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.YearMonthDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.MonthDaySerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.YearMonthSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.YearSerializer;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.MonthDay;
import java.time.Year;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.Collection;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;

/**
 * json 工具类；对 jackson 的简单封装；实现 json <--> object 的相互转换
 *
 * @author BenJin Yin
 * @date 2020/4/14
 */
@Slf4j
public final class JsonMapper {
    private final ObjectMapper mapper = new ObjectMapper();

    private JsonMapper() {
        this(null, null);
    }

    private JsonMapper(JsonInclude.Include include) {
        this(include, null);
    }

    /**
     * @param include      Include ；序列化实体类的属性包括哪些；默认所有 :ALWAYS
     * @param indentOutput Boolean ； 是否格式化；true = 格式化；false = 不格式化；默认 true
     */
    private JsonMapper(JsonInclude.Include include, Boolean indentOutput) {
        // ALWAYS：输出 值为 null 的 key
        mapper.setSerializationInclusion(include == null ? JsonInclude.Include.ALWAYS : include)
                // 设置时区
                .setLocale(Locale.CHINA).setTimeZone(TimeZone.getTimeZone("GMT+8"))
                // 设置日期格式
                .setDateFormat(new SimpleDateFormat(DatePattern.LOCAL_DATE_TIME_PATTERN))
                .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
                // true：格式化输出
                .configure(SerializationFeature.INDENT_OUTPUT, indentOutput == null ? true : indentOutput)
                // 序列化 空对象，不抛异常
                .configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false)
                // 反序列化 未知属性，不抛异常
                .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
                // 对 jdk8 时间的支持
                .registerModule(new MyJavaTimeModule());
    }
    public static class MyJavaTimeModule extends SimpleModule {
        private static final long serialVersionUID = 1L;

        public MyJavaTimeModule() {
            super(PackageVersion.VERSION);

            // First deserializers
            addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DatePattern.LOCAL_DATE_TIME_FORMATTER));
            addDeserializer(LocalDate.class, new LocalDateDeserializer(DatePattern.LOCAL_DATE_FORMATTER));
            addDeserializer(LocalTime.class, new LocalTimeDeserializer(DatePattern.LOCAL_TIME_FORMATTER));
            addDeserializer(Year.class, new YearDeserializer(DatePattern.YEAR_FORMATTER));
            addDeserializer(YearMonth.class, new YearMonthDeserializer(DatePattern.YEAR_MONTH_FORMATTER));
            addDeserializer(MonthDay.class, new MonthDayDeserializer(DatePattern.MONTH_DAY_FORMATTER));

            // then serializers:
            addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DatePattern.LOCAL_DATE_TIME_FORMATTER));
            addSerializer(LocalDate.class, new LocalDateSerializer(DatePattern.LOCAL_DATE_FORMATTER));
            addSerializer(LocalTime.class, new LocalTimeSerializer(DatePattern.LOCAL_TIME_FORMATTER));
            addSerializer(Year.class, new YearSerializer(DatePattern.YEAR_FORMATTER));
            addSerializer(YearMonth.class, new YearMonthSerializer(DatePattern.YEAR_MONTH_FORMATTER));
            addSerializer(MonthDay.class, new MonthDaySerializer(DatePattern.MONTH_DAY_FORMATTER));

        }
    }
    public static interface DatePattern {
        /**
         * LocalDateTime
         */
        String LOCAL_DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
        String PURE_LOCAL_DATE_TIME_PATTERN = "yyyyMMddHHmmss";

        /**
         * LocalDate
         */
        String LOCAL_DATE_PATTERN = "yyyy-MM-dd";
        String PURE_LOCAL_DATE_PATTERN = "yyyyMMdd";

        /**
         * LocalTime
         */
        String LOCAL_TIME_PATTERN = "HH:mm:ss";
        String PURE_LOCAL_TIME_PATTERN = "HHmmss";

        /**
         * Year
         */
        String YEAR_PATTERN = "yyyy";

        /**
         * YearMonth
         */
        String YEAR_MONTH_PATTERN = "yyyy-MM";
        String PURE_YEAR_MONTH_PATTERN = "yyyyMM";

        /**
         * MonthDay
         */
        String MONTH_DAY_PATTERN = "MM-dd";
        String PURE_MONTH_DAY_PATTERN = "MMdd";

        String DATETIME_MINUTE_PATTERN = "yyyy-MM-dd HH:mm";
        String CHINESE_DATE_PATTERN = "yyyy年MM月dd日";

        String UTC_PATTERN = "yyyy-MM-dd'T'HH:mm:ss'Z'";

        DateTimeFormatter LOCAL_DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern(LOCAL_DATE_TIME_PATTERN);
        DateTimeFormatter LOCAL_DATE_FORMATTER = DateTimeFormatter.ofPattern(LOCAL_DATE_PATTERN);
        DateTimeFormatter LOCAL_TIME_FORMATTER = DateTimeFormatter.ofPattern(LOCAL_TIME_PATTERN);

        DateTimeFormatter YEAR_FORMATTER = DateTimeFormatter.ofPattern(YEAR_PATTERN);
        DateTimeFormatter YEAR_MONTH_FORMATTER = DateTimeFormatter.ofPattern(YEAR_MONTH_PATTERN);
        DateTimeFormatter MONTH_DAY_FORMATTER = DateTimeFormatter.ofPattern(MONTH_DAY_PATTERN);

        DateTimeFormatter PURE_LOCAL_DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern(PURE_LOCAL_DATE_TIME_PATTERN);
        DateTimeFormatter PURE_LOCAL_DATE_FORMATTER = DateTimeFormatter.ofPattern(PURE_LOCAL_DATE_PATTERN);
        DateTimeFormatter PURE_LOCAL_TIME_FORMATTER = DateTimeFormatter.ofPattern(PURE_LOCAL_TIME_PATTERN);
    }


    /**
     * 全部输出、格式化
     *
     * @return JsonMapper
     */
    public static JsonMapper defaultMapper() {
        return new JsonMapper();
    }

    /**
     * 只输出非Null的属性到Json字符串的Mapper、格式化
     *
     * @return JsonMapper
     */
    public static JsonMapper nonNullMapper() {
        return new JsonMapper(JsonInclude.Include.NON_NULL);
    }

    /**
     * 创建只输出非Null且非Empty(如List.isEmpty)的属性到Json字符串的Mapper、格式化
     *
     * @return JsonMapper
     */
    public static JsonMapper nonEmptyMapper() {
        return new JsonMapper(JsonInclude.Include.NON_EMPTY);
    }

    /**
     * 全部输出、不格式化
     *
     * @return JsonMapper
     */
    public static JsonMapper nonIndentMapper() {
        return new JsonMapper(null, false);
    }

    /**
     * 创建只输出非Null的属性到Json字符串的Mapper、不格式化
     *
     * @return JsonMapper
     */
    public static JsonMapper nonNullAndIndentMapper() {
        return new JsonMapper(JsonInclude.Include.NON_NULL, false);
    }

    /**
     * 对象序列化
     *
     * @param object Object
     * @return String
     */
    public String toJson(Object object) {
        if (object == null) {
            return null;
        }
        try {
            return mapper.writeValueAsString(object);
        } catch (IOException e) {
            log.warn("write to json string error: {}", object, e);
            return null;
        }
    }

    /**
     * 反序列化简单对象，如果JSON字符串为Null或"null"字符串, 返回Null. 如果JSON字符串为"[]", 返回空集合.
     *
     * @param jsonString json
     * @param type       目标对象
     * @param <T>        对象泛型
     * @return type
     */
    public <T> T fromJson(String jsonString, Class<T> type) {
        if (jsonString == null || "".equals(jsonString)) {
            return null;
        }
        try {
            return mapper.readValue(jsonString, type);
        } catch (IOException e) {
            log.warn("parse json string error: {}", jsonString, e);
            return null;
        }
    }

    /**
     * 反序列化 泛型对象
     *
     * @param jsonString json
     * @param type       外部类型
     * @param parameter  泛型
     * @param <T>        外部类型
     * @return T
     */
    public <T, E> T fromJsonParam(String jsonString, Class<T> type, Class<E> parameter) {
        if (jsonString == null || "".equals(jsonString)) {
            return null;
        }
        try {
            JavaType javaType = mapper.getTypeFactory().constructParametricType(type, parameter);
            return (T) mapper.readValue(jsonString, javaType);
        } catch (IOException e) {
            log.warn("parse json string error:{}", jsonString, e);
            return null;
        }
    }

    /**
     * 反序列化 Collection
     *
     * @param jsonString     json
     * @param collectionType Collection
     * @param elementType    元素类型
     * @param <C>            Collection泛型
     * @param <T>            元素类型
     * @return Collection
     */
    public <C extends Collection<T>, T> C fromJsonCollection(String jsonString, Class<C> collectionType, Class<T> elementType) {
        if (jsonString == null || "".equals(jsonString)) {
            return null;
        }
        JavaType javaType = mapper.getTypeFactory().constructCollectionType(collectionType, elementType);
        try {
            return mapper.readValue(jsonString, javaType);
        } catch (IOException e) {
            log.warn("parse json string error:{}", jsonString, e);
            return null;
        }
    }

    /**
     * 反序列化 Map；key  只适用于 StdKeySerializers 中列出的类型；默认使用字符串序列化；使用toString方法
     *
     * @param jsonString json
     * @param mapType    Map
     * @param keyType    key 类型
     * @param valueType  value   类型
     * @param <M>        Map泛型
     * @return Map
     */
    public <M extends Map<K, V>, K, V> M fromJsonMap(String jsonString, Class<M> mapType, Class<K> keyType, Class<V> valueType) {
        if (jsonString == null || "".equals(jsonString)) {
            return null;
        }
        JavaType javaType = mapper.getTypeFactory().constructMapType(mapType, keyType, valueType);
        try {
            return mapper.readValue(jsonString, javaType);
        } catch (IOException e) {
            log.warn("parse json string error:{}", jsonString, e);
            return null;
        }
    }

    /**
     * 序列化 成 JsonNode
     *
     * @param value json
     * @return JsonNode
     */
    public JsonNode toJsonNode(String value) {
        try {
            return mapper.readTree(value);
        } catch (IOException e) {
            log.warn("parse json string error:{}", value, e);
            return null;
        }
    }

    /**
     * 当JSON里只含有Bean的部分属性时，更新一个已存在Bean，只覆盖该部分的属性.
     *
     * @param jsonString json
     * @param object     T
     * @return T
     */
    public <T> T update(String jsonString, T object) {
        try {
            return mapper.readerForUpdating(object).readValue(jsonString);
        } catch (IOException e) {
            log.warn("update json string: {}  to object: {}  error", jsonString, object, e);
            return null;
        }
    }

    /**
     * 输出JSONP格式数据.
     *
     * @param functionName functionName
     * @param object       object
     * @return String
     */
    public String toJsonPo(String functionName, Object object) {
        return this.toJson(new JSONPObject(functionName, object));
    }

    /**
     * 设定使用Enum的toString函数来读写Enum——为False时使用Enum的name()函数來读写Enum, 默认为False.
     *
     * @return JsonMapper
     */
    public JsonMapper enumUseToString() {
        mapper.configure(SerializationFeature.WRITE_ENUMS_USING_TO_STRING, true)
                .configure(DeserializationFeature.READ_ENUMS_USING_TO_STRING, true);
        return this;
    }

    /**
     * 取出Mapper做进一步的设置或使用其他序列化API.
     *
     * @return ObjectMapper
     */
    public ObjectMapper getMapper() {
        return mapper;
    }
}
